package com.csdj.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

@WebServlet("/uploadEmpS")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024, // 设置内存阈值，超过此值将写入磁盘
        maxFileSize = 1024 * 1024,       // 单个文件最大大小为 1MB
        maxRequestSize = 2 * 1024 * 1024 // 整个请求最大大小为 2MB
)
public class UploadEmpServletS extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        try {
            String name = req.getParameter("name");
            System.out.println("Name: " + name);

            Collection<Part> parts = req.getParts();
            for (Part part : parts) {
                System.out.println("文件名: " + part.getName());
                System.out.println("文件大小: " + part.getSize());
                System.out.println("文件类型: " + part.getContentType());
                System.out.println("文件属性: " + part.getSubmittedFileName());

                String fileName = part.getSubmittedFileName();
                if (fileName != null && !fileName.isEmpty()) {
                    String fileSuffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
                    if (".jpg".equals(fileSuffix)) {
                        if (part.getName().equals("img")) {
                            String newFileName = UUID.randomUUID() + fileSuffix;
                            String filePath = "D:\\img";
                            File dir = new File(filePath);
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            part.write(filePath + File.separatorChar + newFileName);
                            System.out.println("文件已成功上传: " + newFileName);
                        } else {
                            System.out.println("文件大小为 0，未上传文件");
                        }
                    } else {
                        System.out.println("文件格式不支持，仅支持 .jpg 格式");
                    }
                } else {
                    System.out.println("文件名为空，未上传文件");
                }
            }
            req.getRequestDispatcher("index.jsp").forward(req, resp);
        } catch (IllegalStateException e) {
            System.out.println("文件大小超出限制: " + e.getMessage());
            resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "文件大小超出限制");
        }
        resp.sendRedirect("index.jsp");
    }

}
